package com.ica.android.ui.command;

import com.ica.R;
import com.ica.model.command.AbstractCommand;
import com.ica.model.command.AcceptCallCommand;
import com.ica.model.command.RejectCallCommand;
import com.ica.model.command.RingingModeCommand;
import com.ica.model.command.SendSmsCommand;
import com.ica.model.command.SilenceModeCommand;
import com.ica.model.command.VibrateModeCommand;

import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.RadioButton;
import android.widget.Toast;
import android.widget.ToggleButton;

public class EditCommandActivity extends CommandActivity {
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        init(R.layout.edit_command);
        
        Bundle extras = getIntent().getExtras();
        long commandId = (Long) extras.get("commandId");
        command = commandFacade.getElement(commandId);
        etName.setText(command.getName());
        setCommandDefined(command);
	}
	
	private void setCommandDefined(AbstractCommand command) {
		ToggleButton acceptCall = (ToggleButton) findViewById(R.id.bAcceptCall);
		ToggleButton rejectCall = (ToggleButton) findViewById(R.id.bRejectCall);
		ToggleButton sendSms = (ToggleButton) findViewById(R.id.bSendSms);
		RadioButton ringingMode = (RadioButton) findViewById(R.id.rRingMode);
		RadioButton silentMode = (RadioButton) findViewById(R.id.rSilentMode);
		RadioButton vibrateMode = (RadioButton) findViewById(R.id.rVibrateMode);
		
		for (AbstractCommand c : command.getCommands()) {
			if (c instanceof AcceptCallCommand)
				acceptCall.setChecked(true);
			else if (c instanceof RejectCallCommand)
				rejectCall.setChecked(true);
			else if (c instanceof SendSmsCommand)
				sendSms.setChecked(true);
			else if (c instanceof RingingModeCommand)
				ringingMode.setChecked(true);
			else if (c instanceof SilenceModeCommand)
				silentMode.setChecked(true);
			else if (c instanceof VibrateModeCommand)
				vibrateMode.setChecked(true);
		}		
	}

	@Override
	protected OnClickListener onClickSave() {	
		return new OnClickListener() {	
			public void onClick(View v) {
				if (etName.getText().toString().equals(""))
					Toast.makeText(EditCommandActivity.this, "The Command's name is required", Toast.LENGTH_SHORT).show();
				else {
					command.setName(etName.getText().toString());
					getCommandDefined(command);
					commandFacade.replaceElement(command.getId(), command);
					setResult(RESULT_OK,null);
					finish();
				}
			}
		};
	}
}
